package com.grape.oauth.qrcode.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import com.grape.constants.OAuthConstant;
import com.grape.entity.SysRole;
import com.grape.entity.SysUser;
import com.grape.enums.VerifyCodeEnum;
import com.grape.feign.UserFeign;
import com.grape.model.SecurityUser;
import com.grape.oauth.qrcode.service.IQrcodeUserDetailService;
import com.grape.redis.service.IRedisService;
import com.grape.result.R;
import com.grape.utils.StringUtils;
import lombok.AllArgsConstructor;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Service
@AllArgsConstructor
public class QrcodeUserDetailServiceImpl implements IQrcodeUserDetailService {

    private final UserFeign userFeign;

    private final IRedisService redisService;

    @Override
    public UserDetails loadUserByUserId(String key, String userId) throws UsernameNotFoundException {
        String value = redisService.get(VerifyCodeEnum.QR_CODE_TIME_OUT.join(key));
        if (StringUtils.isBlank(value)) {
            throw new UsernameNotFoundException("验证码过期或者不存在,请刷新二维码");
        }
        R<SysUser> phoneResult = userFeign.getByUserId(userId);
        if (!phoneResult.isSuccess()) {
            throw new UsernameNotFoundException("用户不存在！");
        }
        SysUser user = phoneResult.getData();
        List<SysRole> roleResult = user.getRoleList();
        if (CollectionUtil.isEmpty(roleResult)) {
            throw new UsernameNotFoundException("获取角色失败");
        }
        List<String> roles = roleResult.stream().map(sysRole -> OAuthConstant.ROLE_PREFIX + sysRole.getCode()).collect(Collectors.toList());
        return SecurityUser.builder()
                .id(user.getId())
                .username(user.getUsername())
                .avatar(user.getAvatar())
                .phone(user.getPhone())
                .password(user.getPassword())
                .isAdmin(user.getIsAdmin())
                .authorities(AuthorityUtils.createAuthorityList(ArrayUtil.toArray(roles, String.class)))
                .build();
    }
}
